<?php

/*
 * SiteContentLogic 站点内容逻辑关系
 * free_dream 2014.4.21
 */

namespace Admin\Logic;

use Think\Controller;

class SiteContentLogic extends Controller {

    public $siteContent, $dbconfig,$sendCount;

    public function _initialize() {
        $this->siteContent = M('SiteContent');
        $this->dbconfig = S('DB_CONFIG_DATA');
        $this->sendCount = empty($this->dbconfig['TIME_SEND_COUNT']) ? 5 : $this->dbconfig['TIME_SEND_COUNT'];
    }

    public function doQueue($type) {
        header("Content-type: text/html; charset=utf-8");
        $condition['timer'] = array('ELT', time()); //定时时间小于等于当前时间
        $condition['status'] = 1; //定时时间小于等于当前时间
        $siteQueueView = D('SiteQueue' . ucwords($type) . 'View');
        $site = M('Site');
        $wait_content_id = M('SiteQueueContent')->getField('content_id',TRUE);
        $field = "site_cateid as catid,content_id,site_id,title,thumb,status,seo_keywords,seo_description,content,catdir,remote_content_id,weibo_content,remote_content_url,create_time as createtime,update_time as updatetime";
        switch ($type) {
            case 'content':
                
                $item_queue = $siteQueueView->where($condition)->field($field)->order('timer')->limit($this->sendCount)->select();
                $siteContentLog = M('SiteContentLog');
                if ($item_queue) {
                    foreach ($item_queue as $value) {
                        $this->setRemoteContent($site, $value,$siteContentLog);
                    }
                }
                break;
            case 'pdf':
                
                $wait_content_id && $condition['content_id'] = array('not in',$wait_content_id);
                $item_pdf = $siteQueueView->where($condition)->field($field)->order('timer')->limit(1)->select(); //每次生成1条
                $siteQueuePdf = M('SiteQueuePdf');
                $siteContent = M('SiteContent');
                if ($item_pdf) {
                    vendor("MPDF.mpdf");
                    $mpdf = new \mPDF('UTF-8', 'A4', '', '', 0, 0, 25, 20,-1,-1,'L');
                    $mpdf->useAdobeCJK = true;
                    $mpdf->SetAutoFont(AUTOFONT_ALL);
                    $mpdf->SetDisplayMode('fullpage');
                    $mpdf->showWatermarkText = true;
                    $mpdf->SetAutoFont();

                    foreach ($item_pdf as $key => $value) {
                        $this->generatePdf($site, $siteQueuePdf, $siteContent, $mpdf, $value);
                    }
                }

                break;
            case 'weibo':
                
                $field = "site_cateid as catid,content_id,site_id,title,thumb,status,seo_keywords,seo_description,content,catdir,remote_content_id,weibo_content,remote_content_url,access_token,expires_in,bind_time";
                $condition['access_token'] = array('neq','');
                $condition['expires_in'] = array('EXP','>=(unix_timestamp()-bind_time-600)');
                $wait_content_id && $condition['content_id'] = array('not in',$wait_content_id);
                $item_weibo = $siteQueueView->where($condition)->field($field)->order('timer')->limit($this->sendCount)->select(); //每次生成5条
                import('Think.Sina.saetv2#ex');
                $weibo_sina_config = C('WEIBO_SDK_SINA');
                $siteQueueWeibo = M('SiteQueueWeibo');
                
                foreach ($item_weibo as $key => $value) {
                    $access_token = $site->getFieldById($value['site_id'],'access_token');
                    if(!empty($access_token)){
                        $c = new \SaeTClientV2($weibo_sina_config['WB_AKEY'], $weibo_sina_config['WB_SKEY'], $access_token);
                    $this->sendWeibo($site, $c, $siteQueueWeibo, $value['title'], $value['content'], $value['content_id'], $value['site_id'], $value['remote_content_url'],$value['weibo_content']);
                    }
                }
                break;
            default:
                $this->error('参数无效！');
                break;
        }
    }

    public function setRemoteContent($site, $content,$siteContentLog) {
        header("Content-type: text/html; charset=utf-8");
        $siteInfo = $this->getSiteInfo($site, $content['site_id'], 'apiurl,weburl');
        $content['site_url'] = $siteInfo['apiurl'];
        if ($content['thumb']) {
            $content['full_thumb'] = $this->dbconfig['WEB_URL'] . $content['thumb'];
        }else{
            $content['full_thumb'] = '';
        }
        $content['weburl'] = $siteInfo['weburl'];
        $content['serverUrl'] = $this->dbconfig['WEB_URL'];
        sendRemoteContent($content,$siteContentLog);
        unset($content);
    }

    public function generatePdf($site, $siteQueuePdf, $siteContent, $mpdf, $value) {
        $siteInfo = $this->getSiteInfo($site, $value['site_id'], 'title,apiurl,weburl,pdf_toppic,pdf_bottompic');

        $pdftop = $this->dbconfig['WEB_URL'] . '/'.C('DB_NAME').$siteInfo['pdf_toppic'];   
        $pdfbottom = $this->dbconfig['WEB_URL'] .'/'.C('DB_NAME'). $siteInfo['pdf_bottompic'];
        
        $title = str_cut($value['title'], 80, '');
        $header = <<<EOF
                        <table width="100%">
                            <tr>
                                <td width="100%" style="background: url({$pdftop}) no-repeat;width:795px;height:50px;" align="center"></td>
                            </tr>
                        </table>
EOF;
        $footer = <<<EOF
                        <table width="100%">
                            <tr>
                                <td width="100%" style="background: url({$pdfbottom});width:795px;height:50px;" align="center"></td>
                            </tr>
                        </table>
EOF;
        $mpdf->SetHTMLHeader($header);
        $mpdf->SetHTMLFooter($footer);
        
        $pdf_title = <<<EOF
                        <div align="center"  style="font-size:20px;">
                            {$title}
                        </div>
EOF;
      
        $mpdf->WriteHTML($pdf_title."<div style='margin-left:15mm;margin-right:15mm;line-height:1.5'>".$value['content']."</div>");
        $savename = $value['content_id'].'_'.uniqid() . rand(1000, 9999) . '.pdf';
        $save_pdf_path_name = C('SAVE_PDF_PATH') . $savename;
        $mpdf->Output($save_pdf_path_name);
        $downpdf = __ROOT__ . substr($save_pdf_path_name, 1); //去掉上传路径最前边的.
        
        if(file_exists('.'.$downpdf)){//判断pdf文件是否存在
            $result = $siteContent->where(array('id' => $value['content_id']))->setField(array('downpdf' => $downpdf));
            if($result){
                $siteQueuePdf->where(array('content_id' => $value['content_id']))->delete();
            }
        }
        $siteQueuePdf->where(array('content_id' => $value['content_id']))->delete();
        
    }

    //获取当前微博内容（140字）
    public function sendWeibo($site, $c, $siteQueueWeibo, $title, $content, $content_id, $site_id, $remote_content_url,$weibo_content) {
        $titleLen = mb_strlen($title, 'UTF-8');
        //140字除去链接的20个字和省略符；剩115字左右，需要说明的是链接：无论文章的链接多长，在微博里都会被替换成短链接，按短链接的长度来计算字数；
        
        $summaryLen = 115 - $titleLen;
        if($weibo_content){//如果指定微博内容存在
            $pubPaper = $this->cutstr_html($weibo_content);
            $pubPaper = mb_substr($pubPaper, 0, 120, 'UTF-8');
            $pubPaper = sprintf('%s%s', $pubPaper, $this->content_url($site, $site_id, $remote_content_url));
        }else{
            $pubPaper = $this->cutstr_html($content);
            if (mb_strlen($pubPaper, 'UTF-8') >= $summaryLen){
                $pubPaper = mb_substr($pubPaper, 0, $summaryLen, 'UTF-8');
            }
            $pubPaper = sprintf('【%s】%s...%s', $title, $pubPaper, $this->content_url($site, $site_id, $remote_content_url));
        }
        
        $ret = $c->update($pubPaper);
        if (isset($ret['error_code']) && $ret['error_code'] > 0) {
            
        } else {
            $siteQueueWeibo->where(array('content_id' => $content_id))->delete();
        }
    }

    //完全的去除html标记
    function cutstr_html($string) {
        $string = strip_tags($string);
//        $string = preg_replace('/n/is', '', $string);
//        $string = preg_replace('/ |　/is', '', $string);
        $string = preg_replace('/&nbsp;/is', ' ', $string);
        return $string;
    }

    function content_url($site, $site_id, $remote_content_url) {
        $siteInfo = $this->getSiteInfo($site, $site_id, 'apiurl,weburl');
        return $siteInfo['weburl'] . $remote_content_url;
    }

    private function getSiteInfo($site, $site_id, $field = '*') {
        $siteInfo = $site->where(array('id' => $site_id))->field($field)->find();
        return $siteInfo;
    }

}
